package org.web.webdisplay.server.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.web.base.domain.ResultDO;
import org.web.base.domain.ViewResultHelper;
import org.web.base.domain.helper.ServiceExceptionHelper;
import org.web.base.domain.helper.ValidationHelper;
import org.web.base.domain.view.ViewResultDTO;
import org.web.webdisplay.sdk.biz.AccountInfoBiz;
import org.web.webdisplay.sdk.dto.AccountInfoDTO;
import org.web.webdisplay.sdk.dto.query.QueryAccountInfoRequest;
import org.web.webdisplay.sdk.dto.query.QueryGroupInfoRequest;
import org.web.webdisplay.server.controller.dto.AccountInfoAndGroupInfoDTO;
import org.web.webdisplay.server.controller.query.QueryAccountInfoAndGroupInfoRequest;
import org.web.webdisplay.server.domain.AccountInfoDO;
import org.web.webdisplay.server.domain.GroupInfoDO;
import org.web.webdisplay.server.domain.query.QueryAccountInfo;
import org.web.webdisplay.server.domain.query.QueryGroupInfo;
import org.web.webdisplay.server.service.AccountInfoService;
import org.web.webdisplay.server.service.GroupInfoService;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@SuppressWarnings("rawtypes")
@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger logger = LogManager.getLogger(UserController.class);

    @Resource
    private AccountInfoBiz accountInfoBiz;

    @Resource
    private AccountInfoService accountInfoService;

    @Resource
    private GroupInfoService groupInfoService;


    @RequestMapping("getUserList")
    @ResponseBody
    public ViewResultDTO<List<AccountInfoDTO>> getUserList(@RequestBody QueryAccountInfoRequest queryAccountInfoRequest) {
        try {
            ResultDO<List<AccountInfoDTO>> resultDO = accountInfoBiz.selectAclResourceList(queryAccountInfoRequest);
            return ViewResultHelper.convertToViewResultByResultDO(resultDO, AccountInfoDTO.class);
        } catch (Exception e) {
            logger.error("查询失败", e);
            return ViewResultHelper.buildViewResultByServiceException(e, "查询失败");
        }
    }

    @RequestMapping("getUserList2")
    @ResponseBody
    public ViewResultDTO<List<AccountInfoDTO>> getUserList2(@RequestBody QueryAccountInfoRequest queryAccountInfoRequest) {
        try {
            ResultDO<List<AccountInfoDTO>> resultDO = accountInfoBiz.selectAclResourceList(queryAccountInfoRequest);
            return ViewResultHelper.convertToViewResultByResultDO(resultDO, AccountInfoDTO.class);
        } catch (Exception e) {
            logger.error("查询失败", e);
            return ViewResultHelper.buildViewResultByServiceException(e, "查询失败");
        }
    }



    @RequestMapping("saveUser")
    @ResponseBody
    public ViewResultDTO saveUser(@RequestBody AccountInfoDTO accountInfoDTO) {
        try {

            ResultDO<AccountInfoDTO> resultDO = accountInfoBiz.saveAccountInfo(accountInfoDTO);
            return ViewResultHelper.convertToViewResultByResultDO(resultDO, AccountInfoDTO.class);
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            return ViewResultHelper.buildViewResultByServiceException(e, null);
        }
    }

    @RequestMapping("batchDeleteUserList")
    @ResponseBody
    public ViewResultDTO<Boolean> batchDeleteUserList(@RequestBody List<Integer> ids) {
        ViewResultDTO viewResultDTO = new ViewResultDTO(false);
        try {
            List<AccountInfoDO> list = new ArrayList<>();
            for (Integer id : ids) {
                AccountInfoDO accountInfoDO = new AccountInfoDO();
                accountInfoDO.setAccountInfoId(id);
                accountInfoDO.setIsDelete("Y");
                list.add(accountInfoDO);
            }
            accountInfoService.updateAccountInfoDOBatch(list);
            viewResultDTO.setResult(true);
            viewResultDTO.setMsg("批量删除成功");
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            return ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDTO;
    }

    @RequestMapping("/selectAccountInfoListByQueryAccountInfoAndGroupInfoRequest")
    @ResponseBody
    public ViewResultDTO<List<AccountInfoDTO>> selectAccountInfoListByQueryAccountInfoAndGroupInfoRequest(@RequestBody QueryAccountInfoAndGroupInfoRequest queryAccountInfoAndGroupInfoRequest) {
        ViewResultDTO<List<AccountInfoDTO>> viewResultDO;
        try {
            // 查询对象校验, 如果调用BIZ层方法，则无需校验，因为BIZ自会进行校验。
            ValidationHelper.validateWithThrow(QueryAccountInfoRequest.class, queryAccountInfoAndGroupInfoRequest.getQueryAccountInfoRequest());
            // 调用BIZ层方法
            QueryAccountInfo queryAccountInfo = new QueryAccountInfo();
            BeanUtils.copyProperties(queryAccountInfoAndGroupInfoRequest.getQueryAccountInfoRequest(), queryAccountInfo);
            ResultDO<List<AccountInfoDO>> selectResult = accountInfoService.selectAccountInfoListResult(queryAccountInfo);
            viewResultDO = ViewResultHelper.convertToViewResultByResultDO(selectResult, AccountInfoDTO.class);
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            viewResultDO = ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDO;
    }

    @RequestMapping("/selectAccountInfoListByQueryAccountInfoAndGroupInfoRequest2")
    @ResponseBody
    public ViewResultDTO<List<AccountInfoAndGroupInfoDTO>> selectAccountInfoListByQueryAccountInfoAndGroupInfoRequest2(@RequestBody QueryAccountInfoAndGroupInfoRequest queryAccountInfoAndGroupInfoRequest) {
        ViewResultDTO<List<AccountInfoAndGroupInfoDTO>> viewResultDO = new ViewResultDTO<>(true);
        List<AccountInfoAndGroupInfoDTO> accountInfoAndGroupInfoDTOList = new ArrayList<>();
        viewResultDO.setData(accountInfoAndGroupInfoDTOList);
        try {
            QueryGroupInfoRequest queryGroupInfoRequest = queryAccountInfoAndGroupInfoRequest.getQueryGroupInfoRequest();
            Set<Integer> groupInfoIds = null;
            Map<Integer, GroupInfoDO> groupInfoMap = null;
            if (queryGroupInfoRequest != null) {
                ValidationHelper.validateWithThrow(QueryGroupInfoRequest.class, queryGroupInfoRequest);
                queryGroupInfoRequest.setAllRecords();
                QueryGroupInfo queryGroupInfo = new QueryGroupInfo();
                BeanUtils.copyProperties(queryGroupInfoRequest, queryGroupInfo);
                List<GroupInfoDO> selectGroupInfoListFromDB = groupInfoService.selectGroupInfoList(queryGroupInfo);
                if (selectGroupInfoListFromDB.isEmpty()) {
                    viewResultDO.setTotalCount(0);
                    return viewResultDO;
                } else {
                    groupInfoIds = selectGroupInfoListFromDB.stream().map(GroupInfoDO::getGroupInfoId).collect(java.util.stream.Collectors.toSet());
                    groupInfoMap = selectGroupInfoListFromDB.stream().collect(java.util.stream.Collectors.toMap(GroupInfoDO::getGroupInfoId, g -> g));
                }
            }

            // 查询对象校验, 如果调用BIZ层方法，则无需校验，因为BIZ自会进行校验。
            QueryAccountInfoRequest queryAccountInfoRequest = queryAccountInfoAndGroupInfoRequest.getQueryAccountInfoRequest();
            if (queryAccountInfoRequest != null) {
                ValidationHelper.validateWithThrow(QueryAccountInfoRequest.class, queryAccountInfoAndGroupInfoRequest.getQueryAccountInfoRequest());
            } else {
                queryAccountInfoRequest = new QueryAccountInfoRequest();
                queryAccountInfoAndGroupInfoRequest.setQueryAccountInfoRequest(queryAccountInfoRequest);
            }
            queryAccountInfoRequest.setGroupInfoIdSet(groupInfoIds);

            // 调用BIZ层方法
            QueryAccountInfo queryAccountInfo = new QueryAccountInfo();
            BeanUtils.copyProperties(queryAccountInfoAndGroupInfoRequest.getQueryAccountInfoRequest(), queryAccountInfo);
            ResultDO<List<AccountInfoDO>> selectAccountInfoListResult = accountInfoService.selectAccountInfoListResult(queryAccountInfo);
            if (selectAccountInfoListResult.isSuccess()) {
                viewResultDO.setTotalCount(selectAccountInfoListResult.getTotalCount());
                List<AccountInfoDO> selectAccountInfoList = accountInfoService.selectAccountInfoList(queryAccountInfo);
                if (groupInfoMap == null) {
                    if (!selectAccountInfoList.isEmpty()) {
                        groupInfoIds = selectAccountInfoList.stream().map(AccountInfoDO::getGroupInfoId).collect(java.util.stream.Collectors.toSet());
                        if (!groupInfoIds.isEmpty()) {
                            QueryGroupInfo queryGroupInfo = new QueryGroupInfo();
                            queryGroupInfo.setGroupInfoIdSet(groupInfoIds);
                            List<GroupInfoDO> selectGroupInfoListFromDB = groupInfoService.selectGroupInfoList(queryGroupInfo);
                            groupInfoMap = selectGroupInfoListFromDB.stream().collect(java.util.stream.Collectors.toMap(GroupInfoDO::getGroupInfoId, g -> g));
                        }
                    }
                }
                for (AccountInfoDO accountInfoDO : selectAccountInfoList) {
                    AccountInfoAndGroupInfoDTO accountInfoAndGroupInfoDTO = new AccountInfoAndGroupInfoDTO();
                    accountInfoAndGroupInfoDTOList.add(accountInfoAndGroupInfoDTO);
                    accountInfoAndGroupInfoDTO.setAccountInfoDO(accountInfoDO);
                    if (groupInfoMap != null) {
                        GroupInfoDO groupInfoDO = groupInfoMap.get(accountInfoDO.getGroupInfoId());
                        accountInfoAndGroupInfoDTO.setGroupInfoDO(groupInfoDO);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            viewResultDO = ViewResultHelper.buildViewResultByServiceException(e, null);
        }
        return viewResultDO;
    }


}
